#!/usr/bin/env python3
import argparse
import subprocess
import sys
import os


def __copy(source, dest):
    cmd = ["cp", "-rv", source, dest]
    return cmd
    pass


def __move(source, dest):
    cmd = ["mv", "-v", source, dest]
    return cmd
    pass


def __del(source, dest):
    cmd = ["rm", "-rfv", source]
    return cmd
    pass


def __compress(source, dest):
    cmd = ["tar", "-czvf", dest, source]
    return cmd
    pass


def __uncompress(source, dest):
    cmd = ["tar", "-czvf", dest, source]
    return cmd
    pass


def __dir(source, dest):
    cmd = ["ls", "-l", source]
    return cmd
    pass


def parse_action(args):
    try:
        # 根据不同操作执行命令
        if args.action == "copy":
            cmd = ["cp", "-rv", args.source, args.dest]
        elif args.action == "move":
            cmd = ["mv", "-v", args.source, args.dest]
        elif args.action == "delete":
            cmd = ["rm", "-rfv", args.source]
        elif args.action == "compress":
            if not args.dest.endswith(".tar.gz"):
                raise ValueError("压缩包必须以 .tar.gz 结尾")
            cmd = ["tar", "-czvf", args.dest, args.source]
        elif args.action == "list":
            cmd = ["ls", "-l", args.source]

        # 执行命令
        result = subprocess.run(
            cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
        )
        print(result.stdout)

    except subprocess.CalledProcessError as e:
        print(f"操作失败（错误码 {e.returncode}）:\n{e.stdout}")
        sys.exit(1)
    except Exception as e:
        print(f"错误: {str(e)}")
        sys.exit(1)


def main():
    # 创建主解析器
    parser = argparse.ArgumentParser(description="文件操作工具")
    subparsers = parser.add_subparsers(dest="action", required=True, help="可用操作")

    # --------------------------
    # 复制操作（需要 source 和 dest）
    # --------------------------
    copy_parser = subparsers.add_parser("copy", help="复制文件/目录")
    copy_parser.add_argument("source", help="源路径")
    copy_parser.add_argument("dest", help="目标路径")

    # --------------------------
    # 移动操作（需要 source 和 dest）
    # --------------------------
    move_parser = subparsers.add_parser("move", help="移动文件/目录")
    move_parser.add_argument("source", help="源路径")
    move_parser.add_argument("dest", help="目标路径")

    # --------------------------
    # 删除操作（仅需要 source）
    # --------------------------
    delete_parser = subparsers.add_parser("delete", help="删除文件/目录")
    delete_parser.add_argument("source", help="源路径")

    # --------------------------
    # 压缩操作（需要 source 和 dest）
    # --------------------------
    compress_parser = subparsers.add_parser("compress", help="压缩文件/目录")
    compress_parser.add_argument("source", help="源路径")
    compress_parser.add_argument("dest", help="压缩包路径（需以 .tar.gz 结尾）")

    # --------------------------
    # 列表操作（无需额外参数）
    # --------------------------
    list_parser = subparsers.add_parser("list", help="列出目录内容")
    list_parser.add_argument(
        "source", nargs="?", default=os.getcwd(), help="目录路径（可选）"
    )

    args = parser.parse_args()
    parse_action(args)


if __name__ == "__main__":
    main()



# #!/usr/bin/env python3
# import argparse
# import subprocess
# import sys
# import os


# def parse_action(args):
#     try:
#         # 验证源文件是否存在
#         if not os.path.exists(args.source):
#             raise FileNotFoundError(f"源文件 '{args.source}' 不存在")

#         # 根据 action 执行不同的操作
#         if args.action == "copy":
#             cmd = ["cp", "-v", args.source, args.dest]
#         elif args.action == "move":
#             cmd = ["mv", "-v", args.source, args.dest]
#         elif args.action == "compress":
#             cmd = ["tar", "-czvf", args.dest, args.source]

#         # 执行命令并捕获输出
#         result = subprocess.run(
#             cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
#         )
#         print(f"操作成功:\n{result.stdout}")

#     except subprocess.CalledProcessError as e:
#         print(f"操作失败 (错误码 {e.returncode}):\n{e.stdout}")
#         sys.exit(1)
#     except Exception as e:
#         print(f"发生错误: {str(e)}")
#         sys.exit(1)


# def main():
#     # 解析命令行参数
#     parser = argparse.ArgumentParser(description="执行文件操作的 Shell 命令")
#     parser.add_argument(
#         "action",
#         choices=["copy", "move", "compress", "cmd"],
#         help="操作类型: copy/move/compress",
#     )
#     parser.add_argument("source", help="源文件路径")
#     parser.add_argument("dest", help="目标文件路径")
#     args = parser.parse_args()

#     parse_action(args)


# if __name__ == "__main__":
#     main()
